<template>
  <div class="interview-schedule">
    <div class="header">
      <h1>{{ isUserMode ? '我的面试日程' : '面试日程' }}</h1>
      <el-button v-if="!isUserMode" type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon> 添加面试日程
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-wrapper">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <!-- 无数据 -->
    <el-empty v-else-if="schedules.length === 0" description="暂无面试日程" />

    <!-- 日程列表 -->
    <div v-else class="schedule-list">
      <el-card 
        v-for="schedule in schedules" 
        :key="schedule.schedule_id"
        shadow="hover"
        class="schedule-card"
      >
        <div class="card-header">
          <div class="header-info">
            <h3>{{ isUserMode ? (schedule.company_name || '未知企业') : (schedule.candidate_name || '未知候选人') }}</h3>
            <span class="position-tag">{{ schedule.position_name || '未知岗位' }}</span>
          </div>
          <el-tag :type="getStatusType(schedule.status)">
            {{ getStatusText(schedule.status) }}
          </el-tag>
        </div>

        <el-descriptions :column="2" border size="small">
          <el-descriptions-item v-if="!isUserMode" label="候选人">
            <el-icon><User /></el-icon>
            <span style="margin-left: 5px;">{{ schedule.candidate_name || '未知候选人' }}</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="isUserMode" label="企业">
            <el-icon><User /></el-icon>
            <span style="margin-left: 5px;">{{ schedule.company_name || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="岗位">
            {{ schedule.position_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            <el-icon><Clock /></el-icon>
            {{ formatDateTime(schedule.start_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="地点">
            <el-icon><Location /></el-icon>
            {{ schedule.location || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人" v-if="schedule.contact_person">
            <el-icon><User /></el-icon>
            {{ schedule.contact_person }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话" v-if="schedule.contact_phone">
            <el-icon><Phone /></el-icon>
            {{ schedule.contact_phone }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="!isUserMode" class="actions">
          <el-button type="warning" size="small" @click="editSchedule(schedule)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button type="danger" size="small" @click="deleteSchedule(schedule.schedule_id)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="pagination.pages > 1"
      class="pagination"
      :current-page="pagination.current"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      layout="prev, pager, next, total"
      @current-change="handlePageChange"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.schedule_id ? '编辑面试日程' : '添加面试日程'"
      width="600px"
    >
      <el-form :model="formData" label-width="100px" v-loading="candidatesLoading">
        <el-form-item label="候选人" required>
          <el-select 
            v-model="formData.user_id" 
            placeholder="请选择候选人"
            filterable
            style="width: 100%"
            @change="handleCandidateChange"
          >
            <el-option
              v-for="candidate in candidates"
              :key="candidate.userId"
              :label="candidate.username"
              :value="candidate.userId"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>{{ candidate.username }}</span>
                <el-tag size="small" type="info">{{ candidate.jobName }}</el-tag>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">仅显示状态为"面试中"的申请人，选择后自动填充岗位</div>
        </el-form-item>
        <el-form-item label="岗位名称">
          <el-input v-model="formData.position_name" placeholder="选择候选人后自动填充" />
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-date-picker
            v-model="formData.start_time"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="formData.location" placeholder="请输入面试地点" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="formData.contact_person" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="formData.contact_phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待确认" :value="1" />
            <el-option label="已确认" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSchedule">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Loading, Edit, Delete, Clock, Location, User, Phone 
} from '@element-plus/icons-vue'
import instance from '@/utils/request'
import useStore from '@/store'
import { getEnterpriseApplications } from '@/api/enterprise'

const route = useRoute()
const store = useStore()
const schedules = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const candidatesLoading = ref(false)
const candidates = ref([])
const pagination = ref({
  current: 1,
  pageSize: 5,
  total: 0,
  pages: 0
})

// 判断是否为用户端（/interview/schedule）还是企业端（/frontend/interview-schedule）
const isUserMode = computed(() => route.path.startsWith('/interview'))

// 获取当前企业ID（仅企业端使用）
const currentEnterpriseId = computed(() => store.app.enterpriseId)

// 获取当前用户ID（仅用户端使用）
const currentUserId = computed(() => store.app.userId)

const formData = ref({
  schedule_id: null,
  user_id: null,
  company_id: null,
  company_name: '',
  position_name: '',
  start_time: '',
  location: '',
  contact_person: '',
  contact_phone: '',
  status: 1
})

// 加载日程列表
const loadSchedules = async (page = 1) => {
  // 用户端：按用户ID查询；企业端：按企业ID查询
  if (isUserMode.value) {
    if (!currentUserId.value) {
      console.warn('未找到用户ID，跳过加载日程')
      return
    }
  } else {
    if (!currentEnterpriseId.value) {
      console.warn('未找到企业ID，跳过加载日程')
      return
    }
  }
  
  loading.value = true
  try {
    const params = { 
      page, 
      pageSize: 5
    }
    
    // 根据模式添加不同的查询参数
    if (isUserMode.value) {
      params.user_id = currentUserId.value
    } else {
      params.company_id = currentEnterpriseId.value
    }
    
    const res = await instance.request({
      method: 'GET',
      url: '/interview-schedule',
      params
    })

    if (res && res.code === 200) {
      schedules.value = res.data || []
      if (res.pagination) {
        pagination.value = res.pagination
      }
    } else {
      schedules.value = []
      if (!isUserMode.value) {
        ElMessage.error(res?.message || '获取日程列表失败')
      }
    }
  } catch (e) {
    console.error('获取日程列表失败:', e)
    // 列表加载失败时不弹出提示，静默处理
    schedules.value = []
  } finally {
    loading.value = false
  }
}

// 分页处理
const handlePageChange = (page) => {
  pagination.value.current = page
  loadSchedules(page)
}

// 获取候选人列表（状态为interviewing的申请人）
const fetchCandidates = async () => {
  if (!currentEnterpriseId.value) {
    ElMessage.warning('未找到企业信息')
    return
  }
  
  candidatesLoading.value = true
  try {
    const response = await getEnterpriseApplications(currentEnterpriseId.value, {
      status: 'interviewing',
      page: 1,
      pageSize: 100
    })
    
    const applications = response?.data?.list || response?.list || []
    
    // 转换为候选人列表
    candidates.value = applications.map(app => ({
      userId: app.userId,
      username: app.username || app.userName || `用户${app.userId}`, // 优先使用关联查询的username，其次使用userName字段
      jobName: app.job?.jobName || app.jobName || '未知岗位',
      applicationId: app.applicationId
    }))
    
    console.log(`✅ 获取到 ${candidates.value.length} 个候选人:`, candidates.value)
  } catch (error) {
    console.error('获取候选人列表失败:', error)
    ElMessage.error('获取候选人列表失败')
    candidates.value = []
  } finally {
    candidatesLoading.value = false
  }
}

// 处理候选人选择变化
const handleCandidateChange = (userId) => {
  // 根据选择的用户ID找到对应的候选人信息
  const selectedCandidate = candidates.value.find(c => c.userId === userId)
  
  if (selectedCandidate) {
    // 自动填充岗位名称
    formData.value.position_name = selectedCandidate.jobName
    console.log(`✅ 已选择候选人：${selectedCandidate.username}，岗位：${selectedCandidate.jobName}`)
  }
}

// 显示添加对话框
const showAddDialog = async () => {
  formData.value = {
    schedule_id: null,
    user_id: null,
    company_id: currentEnterpriseId.value,
    company_name: '',
    position_name: '',
    start_time: '',
    location: '',
    contact_person: '',
    contact_phone: '',
    status: 1
  }
  
  // 获取候选人列表
  await fetchCandidates()
  dialogVisible.value = true
}

// 编辑日程
const editSchedule = async (schedule) => {
  formData.value = {
    ...schedule,
    start_time: schedule.start_time
  }
  
  // 编辑时也需要获取候选人列表
  await fetchCandidates()
  dialogVisible.value = true
}

// 保存日程
const saveSchedule = async () => {
  // 验证必填字段
  if (!formData.value.user_id) {
    ElMessage.warning('请选择候选人')
    return
  }
  
  if (!formData.value.start_time) {
    ElMessage.warning('请选择开始时间')
    return
  }

  if (!currentEnterpriseId.value) {
    ElMessage.error('未找到企业信息，请先登录')
    return
  }

  try {
    // 准备提交数据
    const submitData = {
      ...formData.value,
      company_id: currentEnterpriseId.value
    }
    
    const method = formData.value.schedule_id ? 'PUT' : 'POST'
    const url = formData.value.schedule_id
      ? `/interview-schedule/${formData.value.schedule_id}`
      : '/interview-schedule'

    const res = await instance.request({
      method,
      url,
      data: submitData
    })

    if (res && (res.code === 200 || res.code === 201)) {
      ElMessage.success(formData.value.schedule_id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      await loadSchedules(pagination.value.current)
    } else {
      ElMessage.error(res?.message || '操作失败')
    }
  } catch (e) {
    console.error('保存失败:', e)
    ElMessage.error('操作失败')
  }
}

// 删除日程
const deleteSchedule = async (scheduleId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个面试日程吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const res = await instance.request({ method: 'DELETE', url: `/interview-schedule/${scheduleId}` })
    if (res && res.code === 200) {
      ElMessage.success('删除成功')
      await loadSchedules(pagination.value.current)
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除失败:', e)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待确认',
    2: '已确认',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status] || ''
}

onMounted(() => {
  loadSchedules()
})
</script>

<style scoped>
.interview-schedule {
  width: 100%;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  color: #333;
  font-size: 28px;
}

.loading-wrapper {
  text-align: center;
  padding: 60px 0;
  color: #666;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.is-loading {
  font-size: 24px;
}

.schedule-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.schedule-card {
  transition: all 0.3s;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.position-tag {
  font-size: 14px;
  color: #606266;
  background: #f4f4f5;
  padding: 4px 12px;
  border-radius: 4px;
}

.actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>

